package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Autowired
    SetmealDishMapper setmealDishMapper;

    private final String patternStr = "dish_list_";
    /**
     * 保存风味和菜品
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavors(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //保存菜品信息
        dishMapper.save(dish);

        Long dishId = dish.getId();
        //保存菜品口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        for (DishFlavor flavor:flavors) {
            flavor.setDishId(dishId);
        }
        if (flavors.size() != 0 && flavors != null){
            dishFlavorMapper.batchInsert(flavors);
        }

        clearCache(patternStr+dish.getCategoryId());
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 通过id查询菜品
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {

        DishVO dishVO = dishMapper.getById(id);

        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        dishVO.setFlavors(flavors);

        return dishVO;
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        DishVO dishVO = null;
        List<DishFlavor> flavors = null;
        //在售商品不能删除
        for (Long id: ids) {
            dishVO = this.getById(id);
            flavors = dishVO.getFlavors();

            if (dishVO != null && dishVO.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //有关联套餐的不能删除
        Long setmealCount = setmealDishMapper.countSetmealByDishId(ids);
        if ( setmealCount != 0 && setmealCount != null){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除口味
        List<Long> flavorIds = new ArrayList<>();
        for (DishFlavor flavor:flavors) {
            flavorIds.add(flavor.getId());
        }

        if (flavorIds!=null && flavorIds.size() != 0){
            dishFlavorMapper.batchDelete(flavorIds);
        }

        //删除菜品
        if (ids.size()!=0 && ids != null){
            dishMapper.batchDelete(ids);
        }

        clearCache(patternStr+"*");
    }


    /**
     * 修改菜品信息
     * @param dishDTO
     */
    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        //1.修改菜品信息
        dishMapper.update(dish);

        //2.修改菜品口味
        if (flavors!=null && flavors.size()!=0){
            //2.1删除原来的口味信息
            List<Long> flavorIds = new ArrayList<>();
            for (DishFlavor flavor:flavors) {
                flavorIds.add(flavor.getId());
            }

            dishFlavorMapper.batchDelete(flavorIds);

            //2.2新增菜品口味

            for (DishFlavor flavor:flavors) {
                flavor.setDishId(dish.getId());
            }
            dishFlavorMapper.batchInsert(flavors);
        }

        clearCache(patternStr+"*");
    }

    /**
     * 菜品停售和启售
     * @param id
     */
    @Override
    public void saleAndHaltSale(Long id,Integer status) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);

        clearCache(patternStr+"*");
    }

    /**
     * 通过分类id查找菜品
     * @param id
     * @return
     */
    @Override
    public List<Dish> getListByCategoryId(Long id) {
        List<Dish> dishList = dishMapper.getByCategoryId(id);
        return dishList;
    }



    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        //读取缓存数据
        String key = "dish_list_"+dish.getCategoryId();

        ValueOperations valueOperations = redisTemplate.opsForValue();

        List<DishVO> dishVOList;
        dishVOList = (List<DishVO>)valueOperations.get(key);

        //没有缓存数据就查数据库
        if (dishVOList==null){
            List<Dish> dishList = dishMapper.list(dish);
            dishVOList = new ArrayList<>();

            for (Dish d : dishList) {
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(d,dishVO);

                //根据菜品id查询对应的口味
                List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
                dishVO.setFlavors(flavors);
                dishVOList.add(dishVO);
            }
            //缓存数据
            valueOperations.set(key,dishVOList);
        }

        return dishVOList;
    }


    /**
     * 清除redis缓存
     * @param pattern
     */
    private void clearCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
}
